﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WebAppMatrix.Extensions
{
    public class ConfigurationExtensions
    {
        public static T GetAppSettingValue<T>(string key)
        {
            if (key.IsNullOrEmpty())
            {
                throw new ArgumentNullException("key");
            }

            var linq = from item in System.Configuration.ConfigurationManager.AppSettings.AllKeys 
                       where item.ToLower() == key.ToLower() select item;
            if (linq.Count() > 0)
            {
                return ReflectionExtensions.ConvertTo<T>(System.Configuration.ConfigurationManager.AppSettings[linq.First()]);
            }
            else
            {
                throw new MatrixException("指定的Key不存在");
            }
        }

        public static T GetAppSettingValue<T>(string key, T defaultValue)
        {
            if (key.IsNullOrEmpty())
            {
                throw new ArgumentNullException("key");
            }

            var linq = from item in System.Configuration.ConfigurationManager.AppSettings.AllKeys
                       where item.ToLower() == key.ToLower()
                       select item;
            if (linq.Count() > 0)
            {
                return ReflectionExtensions.ConvertTo<T>(System.Configuration.ConfigurationManager.AppSettings[linq.First()]);
            }
            else
            {
                return defaultValue;
            }
        }
    }
}
